package com.cuhk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cuhk.gulimall.product.dao.CategoryBrandRelationDao;
import com.cuhk.gulimall.product.entity.CategoryBrandRelationEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuhk.common.utils.PageUtils;
import com.cuhk.common.utils.Query;

import com.cuhk.gulimall.product.dao.BrandDao;
import com.cuhk.gulimall.product.entity.BrandEntity;
import com.cuhk.gulimall.product.service.BrandService;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 获取Key
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        // 传输过来的key不是空的
        // 说明用户在搜索框中，输入了关键字
        // 需要根据关键字检索
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void updateCascade(BrandEntity brand) {
        this.updateById(brand);
        // 客户端传过来的brand实体数据品牌名称字段不是空的
        // 说明品牌名称得到了更新
        // 此时应该进行冗余数据同步
        if(!StringUtils.isEmpty(brand.getName())) {
            CategoryBrandRelationEntity categoryBrandRelation = new CategoryBrandRelationEntity();
            categoryBrandRelation.setBrandId(brand.getBrandId());
            categoryBrandRelation.setBrandName(brand.getName());
            UpdateWrapper<CategoryBrandRelationEntity> wrapper = new UpdateWrapper<>();
            wrapper.eq("brand_id", brand.getBrandId());
            categoryBrandRelationDao.update(categoryBrandRelation, wrapper);
        }
    }

}